package com.yc.chatroom.common.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;

public class MD5SignUtil {
    public static String generateSign(Map<String, String> params, String secretKey) {
        // 将参数以参数名的字典升序排序
        Map<String, String> sortParams = new TreeMap<>(params);
        Set<Entry<String, String>> entrys = sortParams.entrySet();

        // 遍历排序的字典,并拼接"key=value"格式
        StringBuilder baseString = new StringBuilder();
        for (Entry<String, String> entry : entrys) {
            baseString.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        }
        if (null == secretKey && baseString.length() != 0) {
            baseString.deleteCharAt(baseString.length() - 1);
        } else {
            baseString.append("key=").append(secretKey);
        }

        // 使用MD5对待签名串求签
        return toMd5(baseString.toString());
    }
    
    public static String toMd5(String str) {
    	byte[] bytes = null;
        MessageDigest md5;
        try {
            md5 = MessageDigest.getInstance("MD5");
//            log.debug("MD5待签名字符串：" + str);
            try {
                bytes = md5.digest(str.getBytes("UTF-8"));
            } catch (UnsupportedEncodingException e) {
//                log.error("MD5签名出错", e);
            }
        } catch (NoSuchAlgorithmException e) {
//            log.error("MD5签名出错", e);
        }

        // 将MD5输出的二进制结果转换为小写的十六进制
        StringBuilder sign = new StringBuilder();
        for (byte aByte : bytes) {
            String hex = Integer.toHexString(aByte & 0xFF);
            if (hex.length() == 1) {
                sign.append("0");
            }
            sign.append(hex);
        }
        return sign.toString();
    }

}
